//
//  ContentPhotoSource.m
//  KeYin
//
//  Created by Sean Chen on 6/5/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ContentPhotoSource.h"


@implementation ContentPhotoSource

@synthesize title = _title;

///////////////////////////////////////////////////////////////////////////////////////////////////
// NSObject


- (id)initWithPhotos:(NSMutableArray *)photos {
    self = [super init];
    if (self) {
        _photos = [photos copy];
        
        for (int i = 0; i < _photos.count; ++i) {
            id<TTPhoto> photo = [_photos objectAtIndex:i];
            if ((NSNull*)photo != [NSNull null]) {
                photo.photoSource = self;
                photo.index = i;
            }
        }
    }
    return self;
}

- (void)dealloc {
    TT_RELEASE_SAFELY(_photos);
    TT_RELEASE_SAFELY(_title);
    [super dealloc];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// TTModel

- (BOOL)isLoading {
    return NO;
    //return !!_fakeLoadTimer;
}

- (BOOL)isLoaded {
    return !!_photos;
}

- (void)load:(TTURLRequestCachePolicy)cachePolicy more:(BOOL)more {
    
    [_delegates perform:@selector(modelDidStartLoad:) withObject:self];
    
    NSMutableArray* newPhotos = [NSMutableArray array];
    
    for (int i = 0; i < _photos.count; ++i) {
        id<TTPhoto> photo = [_photos objectAtIndex:i];
        if ((NSNull*)photo != [NSNull null]) {
            [newPhotos addObject:photo];
        }
    }
    
    [_photos release];
    _photos = [newPhotos retain];
    
    for (int i = 0; i < _photos.count; ++i) {
        id<TTPhoto> photo = [_photos objectAtIndex:i];
        if ((NSNull*)photo != [NSNull null]) {
            photo.photoSource = self;
            photo.index = i;
        }
    }
    
    [_delegates perform:@selector(modelDidFinishLoad:) withObject:self];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// TTPhotoSource

- (NSInteger)numberOfPhotos {
    return _photos.count;
}

- (NSInteger)maxPhotoIndex {
    return _photos.count-1;
}

- (id<TTPhoto>)photoAtIndex:(NSInteger)photoIndex {
    if (photoIndex < _photos.count) {
        id photo = [_photos objectAtIndex:photoIndex];
        if (photo == [NSNull null]) {
            return nil;
        } else {
            return photo;
        }
    } else {
        return nil;
    }
}

@end


@end
